In [2]:
%pip install -q mlxtend
In [3]:
# ================================================================
# LAB 9. REGRESSION MODEL SELECTION
#
# STAT 415/615 - Regression
#
# Topics:
#   1. Best-subset selection
#   2. Forward, backward, and bidirectional stepwise selection
#   3. Model comparison using adjusted R2, Mallows Cp, AIC, BIC
#   4. Model validation using a testing sample
#
# Dataset: HOME_SALES.csv
# Response variable: SALES_PRICE
# ================================================================


# ================================================================
# PART 0. PREPARATION
# ================================================================

# Install mlxtend, a library for selecting regression predictors.
# This command is needed only once per Colab session.

%pip install -q mlxtend


# Import the required libraries.

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

from mlxtend.feature_selection import ExhaustiveFeatureSelector
In [4]:
# Load the HOME_SALES dataset directly from the course website.

HOMES = pd.read_csv(
    "https://dr-baron.github.io/415-615/Data/HOME_SALES.csv"
)

# Examine the first five observations.

print(HOMES.head())

# Check the number of observations and variables.

print("\nData dimensions:", HOMES.shape)
   ID  SALES_PRICE  FINISHED_AREA  BEDROOMS  BATHROOMS  GARAGE_SIZE  \
0   1        360.0           3032         4          4            2   
1   2        340.0           2058         4          2            2   
2   3        250.0           1780         4          3            2   
3   4        205.5           1638         4          2            2   
4   5        275.5           2196         4          3            2   

   YEAR_BUILT  STYLE  LOT_SIZE AIR_CONDITIONER POOL QUALITY HIGHWAY  
0        1972      1     22221             YES   NO  MEDIUM      NO  
1        1976      1     22912             YES   NO  MEDIUM      NO  
2        1980      1     21345             YES   NO  MEDIUM      NO  
3        1963      1     17342             YES   NO  MEDIUM      NO  
4        1968      3     21786             YES   NO  MEDIUM      NO  

Data dimensions: (522, 13)
In [5]:
# ================================================================
# PART 1. BEST-SUBSET SELECTION
# ================================================================

# The purpose of best-subset selection is to find the best
# regression model containing k predictors, for each model size k.
#
# For example:
#   Best model with 1 predictor
#   Best model with 2 predictors
#   Best model with 3 predictors
#   ...
#
# We use the ExhaustiveFeatureSelector() function from mlxtend.
#
# The search considers all combinations of predictor columns
# up to the specified maximum model size.
#
# We exclude ID because it is an observation identifier,
# not a meaningful explanatory variable.


Y = HOMES["SALES_PRICE"]

X = HOMES.drop(columns=["ID", "SALES_PRICE"])


# Regression requires numerical predictors.
#
# STYLE is coded numerically, but represents categories.
# We therefore convert it to a categorical variable.
#
# pd.get_dummies() creates indicator variables for categorical
# predictors such as STYLE, QUALITY, POOL, and HIGHWAY.
#
# drop_first=True omits one category from each group to avoid
# perfect multicollinearity with the intercept.

X["STYLE"] = X["STYLE"].astype("category")

X = pd.get_dummies(X, drop_first=True, dtype=float)


# Define a function that fits an ordinary least-squares
# regression using any specified subset of predictors.
#
# statsmodels automatically calculates:
#   R-squared
#   Adjusted R-squared
#   AIC
#   BIC
#   SSE
#   Residual mean square
#   Regression coefficients and their standard errors


def fit_model(columns):

    reg = sm.OLS(
        Y,
        sm.add_constant(X[list(columns)], has_constant="add")
    ).fit()

    return reg
In [6]:
# ------------------------------------------------
# 1A. Find the best subsets of sizes 1 through 8
# ------------------------------------------------

# ExhaustiveFeatureSelector examines every combination
# containing 1, 2, ..., 8 predictor columns.
#
# scoring="r2" selects the model with the largest R-squared
# among models of the same size.
#
# cv=0 means that models are evaluated using the entire
# dataset, without cross-validation.
#
# This is appropriate for reproducing R's regsubsets().
#
# The calculation may take several minutes.


best = ExhaustiveFeatureSelector(
    LinearRegression(),
    min_features=1,
    max_features=8,
    scoring="r2",
    cv=0,
    print_progress=False
)

best.fit(X, Y)
Out[6]:
ExhaustiveFeatureSelector(cv=0, estimator=LinearRegression(),
                          feature_groups=[[0], [1], [2], [3], [4], [5], [6],
                                          [7], [8], [9], [10], [11], [12]],
                          max_features=8, print_progress=False, scoring='r2')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
ExhaustiveFeatureSelector(cv=0, estimator=LinearRegression(),
                          feature_groups=[[0], [1], [2], [3], [4], [5], [6],
                                          [7], [8], [9], [10], [11], [12]],
                          max_features=8, print_progress=False, scoring='r2')
LinearRegression()
LinearRegression()
In [7]:
# ------------------------------------------------
# 1B. Compare the best models
# ------------------------------------------------

# For each model size, calculate:
#
# Adjusted R-squared:
#   Rewards goodness of fit but penalizes extra predictors.
#   Larger values are preferred.
#
# Mallows Cp:
#   Compares the model's SSE with the residual variance
#   estimated from the full model.
#   Smaller values are preferred, especially when Cp
#   is reasonably close to the number of parameters.
#
# BIC:
#   Penalizes model complexity more strongly than AIC.
#   Smaller values are preferred.


# Estimate the error variance using the full regression model.

full = fit_model(X.columns)

sigma2 = full.mse_resid


# Collect model-selection statistics in a table.

results = []

for k in range(1, 9):

    # Find all subsets containing exactly k predictors.

    candidates = [
        v for v in best.subsets_.values()
        if len(v["feature_idx"]) == k
    ]

    # Choose the subset with the largest R-squared.

    subset = max(
        candidates,
        key=lambda v: v["avg_score"]
    )

    # Fit the selected regression.

    reg = fit_model(subset["feature_names"])

    # Calculate Mallows Cp.
    # The number of parameters includes the intercept.

    p = len(reg.params)

    Cp = reg.ssr / sigma2 - len(Y) + 2 * p

    results.append({
        "Size": k,
        "Adjusted R2": reg.rsquared_adj,
        "Cp": Cp,
        "AIC": reg.aic,
        "BIC": reg.bic,
        "Variables": subset["feature_names"]
    })


results = pd.DataFrame(results)

print("\nBEST-SUBSET SELECTION")
print(results.to_string(index=False))
BEST-SUBSET SELECTION
 Size  Adjusted R2         Cp         AIC         BIC                                                                                       Variables
    1     0.670900 463.645472 6046.694476 6055.209811                                                                                (FINISHED_AREA,)
    2     0.717163 326.027075 5968.610256 5981.383258                                                                     (FINISHED_AREA, YEAR_BUILT)
    3     0.787087 118.638675 5821.363814 5838.394484                                                    (FINISHED_AREA, QUALITY_LOW, QUALITY_MEDIUM)
    4     0.799415  82.855715 5791.218759 5812.507097                                        (FINISHED_AREA, YEAR_BUILT, QUALITY_LOW, QUALITY_MEDIUM)
    5     0.815542  35.972594 5748.457207 5774.003212                              (FINISHED_AREA, YEAR_BUILT, LOT_SIZE, QUALITY_LOW, QUALITY_MEDIUM)
    6     0.821187  20.237870 5733.219678 5763.023351                     (FINISHED_AREA, YEAR_BUILT, LOT_SIZE, STYLE_3, QUALITY_LOW, QUALITY_MEDIUM)
    7     0.822543  17.213193 5730.230570 5764.291910            (FINISHED_AREA, YEAR_BUILT, LOT_SIZE, STYLE_2, STYLE_3, QUALITY_LOW, QUALITY_MEDIUM)
    8     0.823860  14.320991 5727.326750 5765.645758 (FINISHED_AREA, BATHROOMS, YEAR_BUILT, LOT_SIZE, STYLE_2, STYLE_3, QUALITY_LOW, QUALITY_MEDIUM)
In [8]:
# ------------------------------------------------
# 1C. Select the best model using each criterion
# ------------------------------------------------

# Adjusted R2: maximize.
# Cp and BIC: minimize.

print("\nBest model size by adjusted R2:",
      results.loc[results["Adjusted R2"].idxmax(), "Size"])

print("Best model size by Cp:",
      results.loc[results["Cp"].idxmin(), "Size"])

print("Best model size by BIC:",
      results.loc[results["BIC"].idxmin(), "Size"])
Best model size by adjusted R2: 8
Best model size by Cp: 8
Best model size by BIC: 6
In [9]:
# ================================================================
# PART 2. SEQUENTIAL MODEL SELECTION
# ================================================================

# Exhaustive search considers every possible combination
# of predictors. This can be computationally expensive
# when the number of predictors is large.
#
# Sequential procedures consider a smaller number of models.
#
# We study three approaches:
#
# FORWARD SELECTION:
#   Start with the intercept-only model.
#   Add one predictor at a time.
#
# BACKWARD ELIMINATION:
#   Start with the full model.
#   Remove one predictor at a time.
#
# BIDIRECTIONAL SELECTION:
#   Start with the intercept-only model.
#   At each step, consider adding or removing a predictor.
#
# We use AIC as the model-selection criterion.
#
# AIC balances goodness of fit against model complexity.
# Smaller AIC indicates a preferred model.
#
# Unlike R-squared, AIC can increase when unnecessary
# predictors are added.


# ------------------------------------------------
# 2A. Specify the candidate regression terms
# ------------------------------------------------

# Here we use formula notation from statsmodels.
#
# C(STYLE) indicates that STYLE is categorical.
# Other categorical variables containing text are
# automatically handled by statsmodels.
#
# Importantly, stepwise selection treats each categorical
# variable as a single term, even when it requires
# several dummy-variable coefficients.
#
# This matches the treatment of categorical terms in
# R's step() function.


terms = [
    "FINISHED_AREA",
    "BEDROOMS",
    "BATHROOMS",
    "GARAGE_SIZE",
    "YEAR_BUILT",
    "C(STYLE)",
    "LOT_SIZE",
    "AIR_CONDITIONER",
    "POOL",
    "QUALITY",
    "HIGHWAY"
]


# Fit a regression model using a specified list of terms.
#
# An empty list produces the intercept-only model.


def regression(selected):

    formula = "SALES_PRICE ~ " + (
        " + ".join(selected) if selected else "1"
    )

    return smf.ols(formula, data=HOMES).fit()


# ------------------------------------------------
# 2B. Define the stepwise-selection procedure
# ------------------------------------------------

# Python's statsmodels provides regression and AIC,
# but does not have a direct equivalent of R's step().
#
# The following short function performs the selection
# by repeatedly comparing candidate models.
#
# At each step:
#   1. Generate models by adding or removing one term.
#   2. Calculate their AIC values using statsmodels.
#   3. Choose the model with the smallest AIC.
#   4. Stop when no further improvement is possible.


def stepwise(direction):

    # Backward elimination starts with the full model.
    # Forward and bidirectional selection start with
    # the intercept-only model.

    selected = terms.copy() if direction == "backward" else []

    while True:

        candidates = []

        # Models obtained by adding one term.

        if direction in ("forward", "both"):

            candidates += [
                selected + [v]
                for v in terms if v not in selected
            ]

        # Models obtained by removing one term.

        if direction in ("backward", "both"):

            candidates += [
                [v for v in selected if v != term]
                for term in selected
            ]

        # AIC of the current model.

        current_AIC = regression(selected).aic

        if not candidates:
            break

        # Find the candidate model with the smallest AIC.

        best = min(
            candidates,
            key=lambda s: regression(s).aic
        )

        # Stop if AIC cannot be reduced further.

        if regression(best).aic >= current_AIC - 1e-8:
            break

        selected = best

    return regression(selected)


# ------------------------------------------------
# 2C. Forward selection
# ------------------------------------------------

reg_forward = stepwise("forward")

print("\nFORWARD SELECTION")
print("Selected model:", reg_forward.model.formula)
print("Adjusted R2:", reg_forward.rsquared_adj)
print("AIC:", reg_forward.aic)
print("BIC:", reg_forward.bic)


# ------------------------------------------------
# 2D. Backward elimination
# ------------------------------------------------

reg_backward = stepwise("backward")

print("\nBACKWARD ELIMINATION")
print("Selected model:", reg_backward.model.formula)
print("Adjusted R2:", reg_backward.rsquared_adj)
print("AIC:", reg_backward.aic)
print("BIC:", reg_backward.bic)


# ------------------------------------------------
# 2E. Bidirectional selection
# ------------------------------------------------

reg_both = stepwise("both")

print("\nBIDIRECTIONAL SELECTION")
print("Selected model:", reg_both.model.formula)
print("Adjusted R2:", reg_both.rsquared_adj)
print("AIC:", reg_both.aic)
print("BIC:", reg_both.bic)


# ------------------------------------------------
# 2F. Examine the selected regression
# ------------------------------------------------

# Display the complete regression summary for the
# model obtained by bidirectional selection.

print("\nREGRESSION SUMMARY")

print(reg_both.summary())
FORWARD SELECTION
Selected model: SALES_PRICE ~ FINISHED_AREA + QUALITY + YEAR_BUILT + LOT_SIZE + C(STYLE) + BATHROOMS + HIGHWAY + GARAGE_SIZE
Adjusted R2: 0.8258477720608026
AIC: 5723.362538693354
BIC: 5770.196882160063

BACKWARD ELIMINATION
Selected model: SALES_PRICE ~ FINISHED_AREA + BATHROOMS + GARAGE_SIZE + YEAR_BUILT + C(STYLE) + LOT_SIZE + QUALITY + HIGHWAY
Adjusted R2: 0.8258477720608025
AIC: 5723.3625386933545
BIC: 5770.196882160064

BIDIRECTIONAL SELECTION
Selected model: SALES_PRICE ~ FINISHED_AREA + QUALITY + YEAR_BUILT + LOT_SIZE + C(STYLE) + BATHROOMS + HIGHWAY + GARAGE_SIZE
Adjusted R2: 0.8258477720608026
AIC: 5723.362538693354
BIC: 5770.196882160063

REGRESSION SUMMARY
                            OLS Regression Results                            
==============================================================================
Dep. Variable:            SALES_PRICE   R-squared:                       0.829
Model:                            OLS   Adj. R-squared:                  0.826
Method:                 Least Squares   F-statistic:                     248.1
Date:                Wed, 28 Oct 2026   Prob (F-statistic):          7.07e-189
Time:                        15:47:09   Log-Likelihood:                -2850.7
No. Observations:                 522   AIC:                             5723.
Df Residuals:                     511   BIC:                             5770.
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
Intercept         -2345.6942    386.583     -6.068      0.000   -3105.182   -1586.206
QUALITY[T.LOW]     -140.8782     13.817    -10.196      0.000    -168.023    -113.734
QUALITY[T.MEDIUM]  -132.5703     10.196    -13.003      0.000    -152.601    -112.540
C(STYLE)[T.2]       -15.9219      6.852     -2.324      0.021     -29.383      -2.461
C(STYLE)[T.3]       -38.0589      7.751     -4.910      0.000     -53.287     -22.831
HIGHWAY[T.YES]      -36.5320     17.799     -2.052      0.041     -71.500      -1.564
FINISHED_AREA         0.1006      0.007     13.845      0.000       0.086       0.115
YEAR_BUILT            1.2492      0.196      6.378      0.000       0.864       1.634
LOT_SIZE              0.0013      0.000      5.842      0.000       0.001       0.002
BATHROOMS             8.2806      4.023      2.058      0.040       0.376      16.185
GARAGE_SIZE           9.3966      4.927      1.907      0.057      -0.284      19.077
==============================================================================
Omnibus:                       60.032   Durbin-Watson:                   1.313
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              218.481
Skew:                           0.466   Prob(JB):                     3.61e-48
Kurtosis:                       6.029   Cond. No.                     4.17e+06
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.17e+06. This might indicate that there are
strong multicollinearity or other numerical problems.
In [10]:
# ================================================================
# PART 3. MODEL VALIDATION
# ================================================================

# A model that fits the observed data well may not predict
# new observations equally well.
#
# To evaluate predictive performance, we divide the data
# into two parts:
#
# TRAINING SAMPLE:
#   Used to estimate the regression coefficients.
#
# TESTING SAMPLE:
#   Used to evaluate prediction accuracy.
#
# We randomly select 100 observations for testing.
# The remaining observations form the training sample.
#
# random_state=42 ensures that the same observations
# are selected whenever the code is rerun.
#
# This is equivalent to setting a random seed in R.


Xtrain, Xtest, Ytrain, Ytest = train_test_split(
    X, Y,
    test_size=100,
    random_state=42
)


# ------------------------------------------------
# 3A. Fit the full model using the training sample
# ------------------------------------------------

reg = LinearRegression().fit(Xtrain, Ytrain)


# Predict SALES_PRICE for the testing observations.

Yhat = reg.predict(Xtest)


# Calculate the Mean Squared Prediction Error:
#
# MSPE = mean((Ytest - Yhat)^2)
#
# Smaller MSPE indicates better prediction accuracy.

MSPE = mean_squared_error(Ytest, Yhat)

print("\nFULL MODEL")
print("MSPE =", round(MSPE, 2))
FULL MODEL
MSPE = 5494.96
In [11]:
# ------------------------------------------------
# 3B. Fit a reduced model without STYLE
# ------------------------------------------------

# Remove the dummy variables corresponding to STYLE.

style_columns = [
    v for v in X.columns if v.startswith("STYLE_")
]

Xtrain1 = Xtrain.drop(columns=style_columns)
Xtest1 = Xtest.drop(columns=style_columns)


# Fit the reduced regression using the training sample.

reg1 = LinearRegression().fit(Xtrain1, Ytrain)


# Predict the response in the testing sample.

Yhat1 = reg1.predict(Xtest1)


# Calculate MSPE for the reduced model.

MSPE1 = mean_squared_error(Ytest, Yhat1)

print("\nMODEL WITHOUT STYLE")
print("MSPE =", round(MSPE1, 2))
MODEL WITHOUT STYLE
MSPE = 5772.15
In [12]:
# ------------------------------------------------
# 3C. Compare prediction accuracy
# ------------------------------------------------

print("\nMODEL VALIDATION RESULTS")

print("Full model MSPE:", round(MSPE, 2))
print("Reduced model MSPE:", round(MSPE1, 2))

if MSPE < MSPE1:
    print("The full model has a smaller MSPE.")
else:
    print("The reduced model has a smaller MSPE.")


# ================================================================
# END OF LAB 9
# ================================================================
MODEL VALIDATION RESULTS
Full model MSPE: 5494.96
Reduced model MSPE: 5772.15
The full model has a smaller MSPE.
In [ ]:
from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat

# Retrieve the current Colab notebook
notebook = _message.blocking_request(
    "get_ipynb", timeout_sec=60
)["ipynb"]

# Convert the notebook directly to HTML
nb = nbformat.reads(
    notebook if isinstance(notebook, str)
    else __import__("json").dumps(notebook),
    as_version=4
)

html, resources = HTMLExporter().from_notebook_node(nb)

# Save the HTML file
filename = "Py Lab 9 - Regression model building.html"

with open(filename, "w", encoding="utf-8") as f:
    f.write(html)

# Download the HTML file
files.download(filename)
In [ ]: